package org.amphiprion.montrictracv4.task.ludotheque;

import org.amphiprion.montrictracv4.R;
import org.amphiprion.montrictracv4.db.model.Game;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;

public class SynchronizeGameTask extends AsyncTask<Game, Integer, Game> {

	private Context context;
	private ProgressDialog progress;
	private SynchronizeGameListener caller;
	private String gameName = "...";

	public SynchronizeGameTask(Context context, SynchronizeGameListener caller) {
		this.context = context;
		this.caller = caller;
	}

	@Override
	protected Game doInBackground(Game... params) {
		gameName = params[0].name;
		((Activity) context).runOnUiThread(new Runnable() {

			@Override
			public void run() {
				progress.setTitle(gameName);
			}
		});

		return WebGameParser.parse(context, params[0]);
	}

	@Override
	protected void onPreExecute() {
		progress = ProgressDialog.show(context, gameName, context.getString(R.string.import_game, 0), true, true, new DialogInterface.OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				cancel(true);
				caller.importEnded(false);
			}
		});
	}

	public void publishProgress(int gameNumber, int totalGame) {
		publishProgress(R.string.import_game_progress, gameNumber, totalGame);
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		progress.setTitle(gameName);
		progress.setMessage(context.getResources().getString(values[0], values[1], values[2]));
	}

	@Override
	protected void onPostExecute(Game result) {
		progress.cancel();

		if (!isCancelled()) {
			caller.importEnded(result != null);
		}
	}

	public interface SynchronizeGameListener {
		void importEnded(boolean succeed);
	}
}
